package com.ah.shanxi_demo.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author zt 2020/8/21
 */
public class StrUtils {

    /**
     * object 转换 string
     *
     * @param object
     * @return
     */
    public static String syncObjectToStr(Object object) {

        //object 转换 string
        String jsonString = JSON.toJSONString(object);
        //去掉转义斜杠
        String unescapeJava = StringEscapeUtils.unescapeJava(jsonString);

        return String_change(unescapeJava);
    }

    /**
     * object 转换 jsonobject
     *
     * @param object
     * @return
     */
    public static JSONObject syncObjectToJsonObject(Object object) {

        //object 转换 string
        String jsonString = JSON.toJSONString(object);
        //去掉转义斜杠
        String unescapeJava = StringEscapeUtils.unescapeJava(jsonString);

        String stringChange = String_change(unescapeJava);

        JSONObject jsonObject = JSONObject.parseObject(stringChange);

        return jsonObject;
    }

    /**
     * string 转换 jsonobject
     *
     * @param jsonString
     * @return
     */
    public static JSONObject syncObjectToJsonObject(String jsonString) {

        //去掉转义斜杠
        String unescapeJava = StringEscapeUtils.unescapeJava(jsonString);

        String stringChange = String_change(unescapeJava);

        JSONObject jsonObject = JSONObject.parseObject(stringChange);

        return jsonObject;
    }

    /**
     * string 去掉前后两个双引号
     *
     * @param str
     * @return
     */
    public static String String_change(String str) {

        if (StringUtils.isBlank(str)) {
            return "";
        }

        if (str.indexOf("\"") == 0) {
            str = str.substring(1, str.length());
        }

        if (str.lastIndexOf("\"") == (str.length() - 1)) {
            str = str.substring(0, str.length() - 1);
        }

        return str;
    }

}
